const appConfig = require('../appConfig');
const security = require('./md5');
const app = getApp();

let httpRequest = function (opt) {
    let _request = function (opt) {
        return function (cb) {
            let tsNow = Math.floor(new Date().getTime() / 1000);
            let sToken = appConfig.appKey + '|' +  tsNow + '|' + appConfig.appSecret;
            let sDigt = security.hexMD5(sToken);

            let sAppToken = appConfig.appKey + '|' +  tsNow + '|' + sDigt;
            console.log('App-Token:' + sAppToken);

            opt.header = opt.header ||  {};
            opt.header['App-Token'] = sAppToken;

            if (app && app.bearerToken){
                opt.header['Authorization'] = app.bearerToken;
            }

            let successHandler = opt.success;
            opt.success = function (res) {
                successHandler && successHandler(res);
                var ret = res.data;
                if (ret && ret.apiStatus && ret.apiStatus.statusCode == 0){
                    cb(null,ret.result);
                }else{
                    cb(ret.apiStatus);
                }
            };

            let failHandler = opt.fail;
            opt.fail = function (e) {
                failHandler && failHandler(e);
                cb(e);
            }
            wx.request(opt);
        }

    }


    return {
        request: _request
    }
}();

module.exports = httpRequest;
